package cn.rubintry.cardtest;

import com.app.tool.BytesUtil;
import com.app.tool.CharUtil;
import com.lf.emv.jni;
import com.out.outemv.ICAdapter;

/**
 * @author logcat
 */
public class CardReader {
    private ICAdapter icAdapter = ICAdapter.getInstance();
    private String cardno;

    public synchronized int open() {
        return jni.getInstance().rfid_open(0);
    }

    public synchronized void close() {
        jni.getInstance().rfid_close();
    }

    /**
     * 上电
     * @return  0成功
     */
    public synchronized int powerUp() {
        int ret = - 1;
        char[] atr= new char[64];
        int[] atrlen=new int[1];

        return icAdapter.PubICAdapterPowerUp(255, atrlen, atr);
    }

    /**
     * 下电
     * @return
     */
    public synchronized int powerDown() {
        return icAdapter.PubICAdapterPowerDown(255);
    }

    /**
     * 检测是否有卡片  -1 无，0 M1，1 身份证
     * @return
     */
    public synchronized int hasCard() {
        int ret = -1;

        icAdapter.PubICAdapterSelectCard(255);
        ret = icAdapter.PubICAdapterCardIn(255);

        if (ret == 0 || ret == 1) {
            return ret;
        } else {
            return -1;
        }
    }

    /**
     * 获取卡号
     * @return
     */

    public synchronized String getCardNo() {
        int ret = - 1;
        char[] atr= new char[64];
        int[] atrlen=new int[1];
        cardno = "";
        //上电
        ret = icAdapter.PubICAdapterPowerUp(255, atrlen, atr);
        if(ret == 0)
        {
            byte[] data = CharUtil.getBytes(atr);
            cardno = BytesUtil.getBCDString(data, 3, 6).toLowerCase();
            //下电
            powerDown();
        }
        return cardno;
    }


    /**
     * 验证扇区密码
     * @param sec   扇区号0~15
     * @param keytype   密钥类型    0：keyA,1:keyB
     * @param key   密钥
     * @return
     */
    public synchronized int m1AuthKey(int sec, int keytype, char[] key) {
        int ret = jni.getInstance().rfid_m1auth(sec, keytype, key);
        return ret;
    }

    /**
     * 读卡数据
     * @param block 所在扇区的块号 0~3
     * @param data  返回的卡数据
     * @return
     */
    public synchronized int m1Read(int block, char[] data) {
        int ret = jni.getInstance().rfid_m1read(block, data);
        return ret;
    }





    /**
     * 写卡数据
     * @param block 所在扇区的块号 0~3
     * @param data  返回的卡数据
     * @return
     */
    public synchronized int m1Wirte(int block, char[] data) {
        int ret = jni.getInstance().rfid_m1write(block, data);
        return ret;
    }
}
